<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { getAppSetting } from '../../tauriApi';
import { registerMenu, getMenu, buildDefaultMenus, invokeMenuAction } from '../../assets/menus';

const props = defineProps({
  modelValue: { type: Array, default: () => [] },
});
const emit = defineEmits(['update:modelValue']);
const { t, locale } = useI18n();

const items = ref([]);
const hasCustom = ref(false);

onMounted(async () => {
  try {
    const raw = await getAppSetting('menubar');
    if (raw) {
      try { const parsed = JSON.parse(raw); hasCustom.value = Array.isArray(parsed) && parsed.length > 0; } catch {}
    }
  } catch {}
  if (!props.modelValue.length && !hasCustom.value) await buildDefaultMenus(t);
  items.value = props.modelValue.length ? props.modelValue : await getMenu('menubar');
});

watch(() => props.modelValue, async (v) => {
  items.value = v && v.length ? v : await getMenu('menubar');
});

watch(locale, async () => {
  if (!hasCustom.value && !props.modelValue.length) {
    await buildDefaultMenus(t);
    items.value = await getMenu('menubar');
  }
});

const openId = ref('');
const rootRef = ref(null);
const submenuStack = ref([]); // 存储子菜单层级信息 [{ items, x, y, parentEl, selected }]

function toggleOpen(id) {
  openId.value = openId.value === id ? '' : id;
  submenuStack.value = []; // 清空子菜单栈
  try { const { useMenuStore } = require('../../stores/menu.ts'); useMenuStore().setOpenMenu(openId.value); } catch {}
}

function onItemClick(item, e) {
  if (item.enabled === false) return;
  if (item.submenu) return;
  invokeMenuAction(item, e);
  openId.value = '';
  submenuStack.value = [];
}

let hoverTimeout = null;

function onItemMouseEnter(item, event, level = 0) {
  // 清除之前的延迟
  if (hoverTimeout) {
    clearTimeout(hoverTimeout);
    hoverTimeout = null;
  }
  
  // 清除比当前级别更深的子菜单
  while (submenuStack.value.length > level) {
    submenuStack.value.pop();
  }
  
  if (item.submenu && item.submenu.length > 0) {
    // 立即显示子菜单，避免闪烁
    const parentEl = event.target;
    const parentRect = parentEl.getBoundingClientRect();
    let menuRect;
    
    if (level === 0) {
      menuRect = parentEl.closest('[data-menubar-popover="1"]').getBoundingClientRect();
    } else {
      menuRect = parentEl.closest('[data-submenu-level]').getBoundingClientRect();
    }
    
    let x = menuRect.right + 1;
    let y = parentRect.top - 2;
    
    // 防止子菜单超出视窗
    const vw = window.innerWidth;
    const vh = window.innerHeight;
    const estimatedWidth = 320;
    const estimatedHeight = Math.min(item.submenu.length * 28 + 8, 320);
    
    // 水平位置优化 - 如果右侧空间不足，显示在左侧
    if (x + estimatedWidth > vw - 8) {
      x = menuRect.left - estimatedWidth - 1;
    }
    
    // 垂直位置优化 - 确保菜单在视窗内
    if (y + estimatedHeight > vh - 8) {
      y = Math.max(8, vh - estimatedHeight);
    }
    
    // 确保不会超出屏幕边界
    if (x < 8) {
      x = 8;
    }
    if (y < 8) {
      y = 8;
    }
    
    submenuStack.value[level] = {
      items: item.submenu,
      x,
      y,
      parentEl,
      selected: -1
    };
  }
}

function onItemMouseLeave(item, event, level = 0) {
  // 使用较短的延迟，避免子菜单消失太慢
  hoverTimeout = setTimeout(() => {
    // 检查鼠标是否在当前级别或更深级别的子菜单上
    let mouseOverAnySubmenu = false;
    for (let i = level; i < submenuStack.value.length; i++) {
      const submenuEl = document.querySelector(`[data-submenu-level="${i}"]`);
      if (submenuEl?.matches(':hover')) {
        mouseOverAnySubmenu = true;
        break;
      }
    }
    
    // 检查鼠标是否还在父菜单项上
    const parentItem = event.target.closest('.px-3');
    const mouseOverParent = parentItem?.matches(':hover');
    
    if (!mouseOverAnySubmenu && !mouseOverParent) {
      while (submenuStack.value.length > level) {
        submenuStack.value.pop();
      }
    }
  }, 150); // 减少延迟时间，提高响应性
}

function onWindowClick(e) {
  const target = e?.target;
  const root = rootRef.value;
  const inMenubar = root && root.contains ? root.contains(target) : false;
  const inPopover = !!(target && target.closest && target.closest('[data-menubar-popover="1"]'));
  const inSubmenu = !!(target && target.closest && target.closest('[data-submenu-level]'));
  if (inMenubar || inPopover || inSubmenu) return; // ignore inside clicks
  openId.value = '';
  submenuStack.value = [];
}
onMounted(() => window.addEventListener('mousedown', onWindowClick));
onBeforeUnmount(() => window.removeEventListener('mousedown', onWindowClick));

function menus() { return items.value; }

// When a submenu is open, hovering another top-level menu should switch to it
function onTopMenuEnter(id) {
  if (openId.value) {
    openId.value = id;
  }
}
</script>

<template>
  <nav ref="rootRef" class="relative flex items-center gap-1 select-none" data-menubar-root="1">
    <div v-for="menu in menus()" :key="menu.id" class="relative">
      <button class="px-1.5 py-1 text-xs rounded hover:bg-slate-100 dark:hover:bg-neutral-800" @click.stop="toggleOpen(menu.id)" @mouseenter="onTopMenuEnter(menu.id)">
        {{ menu.label }}
      </button>
      <div v-if="openId===menu.id" class="absolute left-0 top-full mt-1 min-w-[220px] overflow-hidden rounded-md border border-panel-border bg-panel-bg shadow-lg z-50" data-menubar-popover="1">
        <div v-for="it in menu.submenu" :key="it.id" class="px-3 py-1.5 text-[12px] text-slate-700 hover:bg-slate-100 dark:text-neutral-300 dark:hover:bg-neutral-800 relative"
             @click.stop="onItemClick(it, $event)"
             @mouseenter="onItemMouseEnter(it, $event, 0)"
             @mouseleave="onItemMouseLeave(it, $event, 0)">
          <span v-if="it.label==='-'" class="block h-px bg-panel-border my-1"></span>
          <template v-else>
            <span>{{ it.label }}</span>
            <span v-if="it.accelerator" class="float-right text-[11px] text-slate-400 dark:text-neutral-500">{{ it.accelerator }}</span>
            <span v-if="it.submenu && it.submenu.length" class="float-right text-slate-400 dark:text-neutral-500 ml-2">
               <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                 <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />
               </svg>
             </span>
          </template>
        </div>
      </div>
      
      <!-- 子菜单层级渲染 -->
       <template v-for="(submenu, level) in submenuStack" :key="'submenu-'+level">
         <div :data-submenu-level="level" 
              class="fixed w-[320px] overflow-hidden rounded-md border border-panel-border bg-panel-bg shadow-lg"
              :style="{ 
                left: submenu.x + 'px', 
                top: submenu.y + 'px',
                zIndex: 60 + level
              }"
              @mouseenter="() => {}" @mouseleave="onItemMouseLeave({}, $event, level)">
           <div class="py-1">
             <div v-for="(subItem, idx) in submenu.items" :key="subItem.id || idx" 
                  class="px-4 py-1.5 text-[12px] text-slate-700 hover:bg-slate-100 dark:text-neutral-300 dark:hover:bg-neutral-800 relative cursor-pointer flex items-center min-h-[28px]"
                  :class="{ 'text-slate-400 dark:text-neutral-600 cursor-default': subItem.enabled === false }"
                  :title="subItem.label"
                  @click.stop="onItemClick(subItem, $event)"
                  @mouseenter="onItemMouseEnter(subItem, $event, level + 1)"
                  @mouseleave="onItemMouseLeave(subItem, $event, level + 1)">
               <span v-if="subItem.label==='-'" class="block h-px bg-slate-200 dark:bg-neutral-700 my-1 w-full"></span>
               <template v-else>
                 <span class="truncate flex-1 pr-2" :title="subItem.label">{{ subItem.label }}</span>
                 <span v-if="subItem.accelerator" class="ml-6 text-[11px] text-slate-400 dark:text-neutral-500">{{ subItem.accelerator }}</span>
                 <span v-if="subItem.submenu && subItem.submenu.length" class="ml-2 text-slate-400 dark:text-neutral-500">
                    <svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                      <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />
                    </svg>
                  </span>
               </template>
             </div>
           </div>
         </div>
       </template>
    </div>
  </nav>
</template>


